{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import pickle\n",
    "import numpy as np\n",
    "np.random.seed(42)\n",
    "import pandas as pd\n",
    "from collections import defaultdict\n",
    "from sklearn.metrics.pairwise import cosine_similarity\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset = \"yelp_new\"\n",
    "sim_metric = \"cos\"\n",
    "topk = 100"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Get the topk similar user"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the llm user embedding\n",
    "user_emb = pickle.load(open(os.path.join(dataset+\"/handled/\", \"usr_emb_np.pkl\"), \"rb\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# calculate the similarity score between users based on llm user embedding\n",
    "if sim_metric == \"sin\":\n",
    "    score_matrix = np.dot(user_emb, user_emb.T)\n",
    "elif sim_metric == \"cos\":\n",
    "    score_matrix = cosine_similarity(user_emb, user_emb)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.hist(score_matrix[0], bins=10)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rank_matrix = np.argsort(-score_matrix, axis=-1)    # user id starts from 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "final_rank_matrix = rank_matrix[:, 1:]\n",
    "final_rank_matrix = final_rank_matrix[:, :topk]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Get the sequence length of each user"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "User = defaultdict(list)\n",
    "seq_len = []\n",
    "usernum, itemnum = 0, 0\n",
    "f = open('./%s/handled/%s.txt' % (dataset, \"inter\"), 'r')\n",
    "for line in f:  # use a dict to save all seqeuces of each user\n",
    "    u, i = line.rstrip().split(' ')\n",
    "    u = int(u)\n",
    "    i = int(i)\n",
    "    usernum = max(u, usernum)\n",
    "    itemnum = max(i, itemnum)\n",
    "    User[u].append(i)\n",
    "\n",
    "for user, seq in User.items():\n",
    "    seq_len.append(len(seq))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sim_user_len = []\n",
    "for sim_user_list in final_rank_matrix:\n",
    "    avg_len = 0\n",
    "    for sim_user in sim_user_list:\n",
    "        avg_len += seq_len[sim_user] / topk\n",
    "    sim_user_len.append(avg_len)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.mean(sim_user_len), np.mean(seq_len)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Select the similar user"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sim_users = []\n",
    "for sim_user_list in final_rank_matrix:\n",
    "    sim_users.append(np.random.choice(sim_user_list, 1)[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "final_rank_matrix.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Save llm embedding based similar users\n",
    "pickle.dump(final_rank_matrix, open(os.path.join(dataset+\"/handled/\", \"sim_user_100.pkl\"), \"wb\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llm",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.5"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
